import json
import os
import requests

import pymysql
from xlutils.copy import copy

import pyautogui
import pytesseract
# 导入库
import xlwings as xw
import time
import calendar
import pandas as pd
import xlrd
import xlwt
from selenium import webdriver
from selenium.webdriver.common.desired_capabilities import DesiredCapabilities
import sys
import arrow
from robot import Robot
Robot_d = Robot()


def yecai_firefox():

    print('启动ie前先关闭ie')
    os.system(r"taskkill /F /IM Firefox.exe")
    # os.system(r"taskkill /F /IM WerFault.exe")
    print('启动ie')
    # time.sleep(30)
    # 打开金蝶
    DesiredCapabilities.INTERNETEXPLORER['ignoreProtectedModeSettings'] = True
    downloads = os.path.join(os.path.expanduser("~"), 'Downloads/').replace('\\', '/')
    # Robot_d.ie_ie("http://ybxbzapp.chinapost.com.cn:8001/")
    # Robot_d.ie_edge("http://ybxbzapp.chinapost.com.cn:8001/")
    Robot_d.firefox("http://10.5.135.101")

    # Robot_d.open_exe("C:\Program Files (x86)\Internet Explorer\Iexplore.exe")
    # Robot_d.ie_open_url("http://ybxbzapp.chinapost.com.cn:8001/OA_HTML/RF.jsp?function_id=28716&resp_id=-1&resp_appl_id=-1&security_group_id=0&lang_code=ZHS&oas=Z8KrqQQsG0vM6DAaiX86wQ..&params=KQ0ueFd3h5ncJDQ0.532EQ")
    time.sleep(3)

    # # 等待1秒
    time.sleep(1)
    time.sleep(5)
    # 账号密码
    # Robot_d.move(400, 275, 2)
    Robot_d.write_text('/html/body/div/div[1]/div/div[2]/div[2]/div/div[2]/form/div[1]/div/div[1]/input', 'mengying4101')
    time.sleep(1)
    Robot_d.write_text('/html/body/div/div[1]/div/div[2]/div[2]/div/div[2]/form/div[2]/div/div/input', 'my@123456')
    time.sleep(1)
    Robot_d.click_herf('/html/body/div/div[1]/div/div[2]/div[2]/div/div[2]/form/div[3]/div/button')  # 确定
    # tests = Robot_d.js_go_text('''
    #                 var per = window.performance || window.mozPerformance || window.msPerformance || window.webkitPerformance || {};
    #                 var network = performance.getEntries() || {};
    #                 return network;
    #             ''')
    # for test in tests:
    #     print(test)
    #     if 'token=' in test['name']:
    #         token = test['name'].split('token=')[1].split('&')[0]
    #         break
    #     else:
    #         token = ''
    tests = Robot_d.js_go_text('''
                        return sessionStorage.getItem("userToken");
                    ''')
    token = json.loads(tests)['v'].replace('"', '')

    time.sleep(3)
    Robot_d.menu_span('.userinfo-currole-text', '//ul[starts-with(@id, "dropdown-menu-")]//li/span[text()="PSC_财务审核"]')
    time.sleep(2)
    Robot_d.click_herf('//div[@class="normal-menus"]//div/div/span[text()="工作流引擎"]')
    time.sleep(2)
    Robot_d.click_herf('//div[starts-with(@class, "menu-item-")]/span[text()="待办任务"]')
    time.sleep(3)
    # 下载待办任务
    Robot_d.css_selector('.el-button--el-btn-primary')
    # Robot_d.click_herf('.el-button--el-btn-primary')
    time.sleep(5)
    pyautogui.keyDown('Altleft')
    pyautogui.keyDown('s')
    pyautogui.keyUp('s')
    pyautogui.keyUp('Altleft')
    time.sleep(2)
    pyautogui.press('Enter')

    # 读取单号，与审核结果对比
    psNo = 'PSA4113012023070000135'
    # 循环输入单号，查找，办理，取数
    Robot_d.write_text('//input[@class="el-input__inner"]', f'{psNo}')
    time.sleep(1)
    Robot_d.click_herf('//div[@class="search__bottom--button"]/button/span[text()="查询"]')
    time.sleep(3)
    # token = Robot_d.click_herf('/html/body/div[1]/div[1]/div/div[3]/div/div[1]/div/section/div[4]/div/div/div/div[3]/div/div[1]/div[4]/div[2]/table/tbody/tr/td[14]/div/span/div/a[2]')
    # 办理
    print(token)
    headers = {
        'Host': '10.5.135.101',
        'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64; rv:70.0) Gecko/20100101 Firefox/70.0',
        'Accept': 'application/json, text/plain, */*',
        'Accept-Language': 'zh-CN,zh;q=0.8,zh-TW;q=0.7,zh-HK;q=0.5,en-US;q=0.3,en;q=0.2',
        'Accept-Encoding': 'gzip, deflate',
        'Authorization': f'Bearer {token}',
        'Content-Type': 'application/json',
        'RoleCode': 'PSC_FIN_APPROVER',
        'Origin': 'http://10.5.135.101',
        'Connection': 'keep-alive',
        'Referer': 'http://10.5.135.101/micro_workflow/task-list',
    }
    data = {
        "pageNum":1,
        "pageSize":10,
        "approvalUser":"mengying4101",
        "sourceNo":f"{psNo}"
    }
    blurl = 'http://10.5.135.101/ycyt-common/ycyt-bcc-workflow/api/workflow/task/myToDoList'
    blresponse = requests.post(blurl, headers=headers, json=data)
    print(blresponse)
    if blresponse.status_code == 200:
        bljson = blresponse.json()
        print(bljson)
    else:
        print('失败')
    time.sleep(5)

    infoNo = bljson['data']['list'][0]['applyNo']

    # Robot_d.iframe_select('iframe')
    # time.sleep(5)
    # a = Robot_d.js_text('input[placeholder="核算公司"]')
    # a = Robot_d.js_text('input[placeholder="请选择"]')     # 费用类型
    # a = Robot_d.js_text('input[placeholder="结算单号"]')
    # a = Robot_d.js_text('input[placeholder="单据来源"]')
    # a = Robot_d.js_text('input[placeholder="创建人"]')
    # a = Robot_d.js_text('input[placeholder="创建时间"]')
    # a = Robot_d.js_text('textarea[placeholder="摘要"]')
    # a = Robot_d.js_text('input[placeholder="付款公司"]')
    # a = Robot_d.js_text('input[placeholder="不含税总金额"]')
    # a = Robot_d.js_text('input[placeholder="总税额"]')
    # a = Robot_d.js_text('input[placeholder="价税总计"]')
    # a = Robot_d.js_text('input[placeholder="预付款核销金额"]')
    # a = Robot_d.js_text('input[placeholder="价税总计"]')
    # a = Robot_d.js_texts('4', 'input[placeholder="请选择"]')    # 支付方式
    # a = Robot_d.js_texts('5', 'input[placeholder="请选择"]')    # 付款条件
    # a = Robot_d.js_text('input[placeholder="供应商名称"]')
    # a = Robot_d.js_text('input[placeholder="收款方名称"]')
    # a = Robot_d.js_text('input[placeholder="收款方账号"]')
    # a = Robot_d.js_text('input[placeholder="支行名称"]')
    # a = Robot_d.js_text('input[placeholder="开户行联行号"]')
    # a = Robot_d.js_text('input[placeholder="原系统合同编号"]')
    # a = Robot_d.js_text('input[placeholder="合同名称"]')

    # 基础信息
    jcxhr = f'http://10.5.135.101/ycyt-common/ycyt-psc-web/pscPsInfo/queryPsInfo?infoNo={infoNo}&sourceSystem=WF'
    jcresponse = requests.get(jcxhr)
    if jcresponse.status_code == 200:
        jcdata = jcresponse.json()
        print(jcdata)
    # Robot_d.js_test('//div[@id="pane-1"]//input[@placeholder="请选择"]')   # , '//div[@class="el-scrollbar"]//span[text()="100条/页"]'
    # time.sleep(3)
    # pyautogui.press('Up', 2, 0.5)
    # pyautogui.press('Enter')
    # num = Robot_d.js_go_text('''
    #         var pe = document.getElementById('pane-1');
    #         return pe.querySelector(\'.el-pagination__total\').textContent;
    #     ''')
    # nums = ''.join(filter(str.isdigit, num))
    # print(int(nums))
    # div_list = []
    # time.sleep(2)
    # for i in range(int(nums)):
    #     row_list = []
    #     for j in range(23):
    #         text_list = Robot_d.class_text('//div[@id="pane-1"]//table[@class="el-table__body"]/tbody/tr[{}]/td[{}]/div'.format(i + 1, j + 1))
    #         # '/html/body/div[1]/div/div/div[4]/div[2]/div[1]/div[2]/div[3]/table/tbody/tr[1]/td[2]/div'
    #         row_list.append(text_list)
    #     div_list.append(row_list)
    # print(div_list)
    # 成本信息
    cbxhr = f'http://10.5.135.101/ycyt-common/ycyt-psc-web/pscPsCost/queryByPsInfo?pageNum=1&pageSize=500&psNo={psNo}&costSettleType=PSC029&type='
    cb_list = []
    cbresponse = requests.get(cbxhr)
    if cbresponse.status_code == 200:
        cbdata = cbresponse.json()
        print(cbdata)
        for code in cbdata['data']['records']:
            cb_list.append(code)
    print(cb_list)
    #
    # # 附件下载
    # Robot_d.click_herf('//div[@id="tab-4"]')
    # Robot_d.js_test(
    #     '//div[@id="pane-4"]//input[@placeholder="请选择"]')  # , '//div[@class="el-scrollbar"]//span[text()="100条/页"]'
    # time.sleep(3)
    # pyautogui.press('Up', 1, 0.5)
    # pyautogui.press('Enter')
    #
    # num4 = Robot_d.js_go_text('''
    #                 var pe = document.getElementById('pane-4');
    #                 return pe.querySelector(\'.el-pagination__total\').textContent;
    #             ''')
    # nums4 = ''.join(filter(str.isdigit, num4))
    # print(int(nums4))
    # time.sleep(2)
    # for i4 in range(int(nums4)):
    #     text_file = Robot_d.class_text('//div[@id="pane-4"]//table[@class="el-table__body"]/tbody/tr[{}]/td[3]/div'.format(i4 + 1))
    #     end_file = Robot_d.class_text('//div[@id="pane-4"]//table[@class="el-table__body"]/tbody/tr[{}]/td[4]/div'.format(i4 + 1))
    #     file_url = 'http://10.5.135.101/ycyt-common/ycyt-psc-web/fileManage/download?contentId=' + text_file
    #     response = requests.get(file_url)
    #     if response.status_code == 200:
    #         save_path = os.path.join(downloads, text_file + '.' + end_file)
    #         with open(save_path, "wb") as file:
    #             file.write(response.content)
    #     else:
    #         print('失败')
    fjxhr = f'http://10.5.135.101/ycyt-common/ycyt-psc-web/pscAttInfo/queryBySheetNo/{psNo}?pageNum=1&pageSize=500&apNo={psNo}'
    fjresponse = requests.get(fjxhr)
    if fjresponse.status_code == 200:
        fjdata = fjresponse.json()
        print(fjdata)
        for code in fjdata['data']['records']:
            attCode = code['attCode']
            attName = code['attName']
            fjaddr = 'http://10.5.135.101/ycyt-common/ycyt-psc-web/fileManage/download?contentId={}'.format(attCode)
            fjrsp = requests.get(fjaddr)
            if fjrsp.status_code == 200:
                fj_path = os.path.join(downloads, attName)
                with open(fj_path, "wb") as file:
                    file.write(fjrsp.content)
            else:
                print('失败')

    # 发票下载
    xhr = f'http://10.5.135.101/ycyt-common/ycyt-psc-web/pscInvInfo/queryByPsNo/{psNo}?pageNum=1&pageSize=500&psNo={psNo}'
    response = requests.get(xhr)
    if response.status_code == 200:
        data = response.json()
        print(data)
        for code in data['data']['records']:
            attCode = code['attCode']
            fpaddr = 'http://10.5.135.101/ycyt-common/ycyt-psc-web/fileManage/download?contentId={}&fileFlag=FP'.format(attCode)
            rsp = requests.get(fpaddr)
            if rsp.status_code == 200:
                save_path = os.path.join(downloads, attCode + '.jpg')
                with open(save_path, "wb") as file:
                    file.write(rsp.content)
            else:
                print('失败')

    # 税额
    taxxhr = f'http://10.5.135.101/ycyt-common/ycyt-psc-web/pscPsInvTax/queryByPsNo/{psNo}?pageNum=1&pageSize=500&psNo={psNo}'
    tax_list = []
    taxresponse = requests.get(taxxhr)
    if taxresponse.status_code == 200:
        taxdata = taxresponse.json()
        print(taxdata)
        for code in taxdata['data']['records']:
            tax_list.append(code)
    print(tax_list)

    #     file_url = 'http://10.5.135.101/ycyt-common/ycyt-psc-web/fileManage/download?contentId=' + text_file
    #     response = requests.get(file_url)
    #     if response.status_code == 200:
    #         save_path = os.path.join(downloads, text_file + '.' + end_file)
    #         with open(save_path, "wb") as file:
    #             file.write(response.content)
    #     else:
    #         print('失败')

    # Robot_d.click_herf('//a[text()="CTR01467136002023040000001"]')
    # # 合同
    # print(token)
    # time.sleep(2)
    # Robot_d.iframe_select('mainIframe')
    # time.sleep(2)
    # a = Robot_d.js_text('input[placeholder="请选择日期"]')
    # print(a)

    # 合同请求
    ctrNo = 'CTR01473400082023070000002'
    ctrVer = '1'
    headers = {
        'Host': '10.5.135.101',
        'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64; rv:70.0) Gecko/20100101 Firefox/70.0',
        'Accept': 'application/json, text/plain, */*',
        'Accept-Language': 'zh-CN,zh;q=0.8,zh-TW;q=0.7,zh-HK;q=0.5,en-US;q=0.3,en;q=0.2',
        'Accept-Encoding': 'gzip, deflate',
        'Authorization': f'Bearer {token}',
        'RoleCode': 'PSC_FIN_APPROVER',
        'Connection': 'keep-alive',
        'Referer': f'http://10.5.135.101/contract/ctrMan/ctrSearch/conEntry/detail?ctrNo={ctrNo}&ctrVer={ctrVer}&token={token}',
    }
    hturl = f'http://10.5.135.101/ycyt-common/ycyt-ctr-manager-web/ctr/contract/getCtrHeadInfoById?ctrNo={ctrNo}&ctrVer={ctrVer}'
    htresponse = requests.get(hturl, headers=headers)
    print(htresponse)
    if htresponse.status_code == 200:
        htjson = htresponse.json()
        print(htjson)
    else:
        print('失败')

    for ht in htjson['data']['fileList']:
        # 下载
        fileUrl = ht['fileUrl']
        fileName = ht['fileName']
        headers = {
            'Host': '10.5.135.101',
            'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64; rv:70.0) Gecko/20100101 Firefox/70.0',
            'Accept': 'application/json, text/plain, */*',
            'Accept-Language': 'zh-CN,zh;q=0.8,zh-TW;q=0.7,zh-HK;q=0.5,en-US;q=0.3,en;q=0.2',
            'Accept-Encoding': 'gzip, deflate',
            'Authorization': f'Bearer {token}',
            'RoleCode': 'PSC_FIN_APPROVER',
            'Connection': 'keep-alive',
            'Referer': f'http://10.5.135.101/contract/ctrMan/ctrSearch/conEntry/detail?ctrNo={ctrNo}&ctrVer=1&token={token}',
        }
        url = f'http://10.5.135.101/ycyt-common/ycyt-ctr-manager-web/ctr/contract/downloadFile?fileUrl={fileUrl}&fileName={fileName}'
        response = requests.get(url, headers=headers)
        if response.status_code == 200:
            save_path = os.path.join(downloads, fileName)
            with open(save_path, "wb") as file:
                file.write(response.content)
            file.close()
        else:
            print('失败')


yecai_firefox()
'http://10.5.135.101/ycyt-common/ycyt-ctr-manager-web/ctr/contract/getCtrHeadInfoById?ctrNo=CTR01467136002023040000001&ctrVer=2'